﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using CodeContrib;

namespace CodeContribBlog.Data
{
	[MetadataType(typeof (PostMetadata))]
	public class Post : SoftDeletableEntity
	{
		private Guid _showIfPrivate;
		private string _slug;
		private string _title;

		public bool AllowComments { get; set; }

		public bool AreCommentsClosed
		{
			get
			{
				if (Blog.NumberOfDaysToComment < 1)
				{
					return false;
				}

				var lastCommentDate = (Comments.Any()) ? Comments.Max(x => x.CreatedAt) : PublishedAt;

				return DateTime.UtcNow - lastCommentDate > TimeSpan.FromDays(Blog.NumberOfDaysToComment);
			}
		}

		public virtual User Author { get; set; }

		public virtual Blog Blog { get; set; }

		public virtual int BlogId { get; set; }

		public string Body { get; set; }

		public virtual ICollection<Comment> Comments { get; set; }

		public DateTime CreatedAt { get; set; }

		public DateTime PublishedAt { get; set; }

		public Guid ShowIfPrivate
		{
			get
			{
				if (_showIfPrivate == Guid.Empty)
				{
					_showIfPrivate = Guid.NewGuid();
				}

				return _showIfPrivate;
			}
			set { _showIfPrivate = value; }
		}

		public string Slug
		{
			get { return _slug; }
			set { _slug = value.ToSlug(); }
		}

		public virtual ICollection<Tag> Tags { get; set; }

		public string Title
		{
			get { return _title; }
			set
			{
				_title = value;

				Slug = _title;
			}
		}

		public Post()
		{
			AllowComments = true;
			Comments = new Collection<Comment>();
			CreatedAt = DateTime.UtcNow;
			PublishedAt = DateTime.UtcNow;
			Tags = new Collection<Tag>();
		}

		public bool IsPublic()
		{
			var now = DateTime.UtcNow;

			return (!IsDeleted && PublishedAt >= now);
		}
	}
}